import i18n from '@/i18n'
import { FlowBoardDataDao } from '@apps/flow/domain/flow-board-data/flow-board-data.dao'
import { Assist, md5 } from '@libs/lhy-common'
import { Body, Controller, Get, Post, Put, Query } from '@nestjs/common'
import { ApiOperation, ApiTags } from '@nestjs/swagger'
import { FlowBoardDataGetByIdDto } from './dto/flow-board-data-get-by-id.dto'
import { FlowBoardDataSaveDto } from './dto/flow-board-data-save.dto'
import { FlowBoardDataUpdateByIdDto } from './dto/flow-board-data-update-by-id.dto'

@ApiTags(i18n.t('app-flow.flow-board-data.flow-board-data.12153237-0'))
@Controller({
  path: 'board_data',
  version: '1',
})
export class FlowBoardDataController {
  constructor(private readonly boardDataDao: FlowBoardDataDao) {}

  @ApiOperation({ summary: i18n.t('app-flow.flow-board-data.flow-board-data.12153237-1') })
  @Get()
  async getById(@Query() param: FlowBoardDataGetByIdDto) {
    const data = Assist.notNull(
      await this.boardDataDao.getById(param.id),
      i18n.t('app-flow.flow-board-data.flow-board-data.12153237-2', { args: [param.id] })
    )

    // 如果dataHash未变化，不返回data数据减少数据量
    if (param.dataHash && param.dataHash === data.dataHash) {
      data.data = undefined
    }

    return data
  }

  @ApiOperation({ summary: i18n.t('app-flow.flow-board-data.flow-board-data.12153237-3') })
  @Post()
  async updateById(@Body() param: FlowBoardDataUpdateByIdDto) {
    const oldData = Assist.notNull(
      await this.boardDataDao.getById(param.id),
      i18n.t('app-flow.flow-board-data.flow-board-data.12153237-2', { args: [param.id] })
    )
    if (oldData.data === param.data) {
      return await this.boardDataDao.updateById(param.id, param)
    } else {
      return await this.boardDataDao.updateById(param.id, {
        ...param,
        dataHash: md5(param.data),
      })
    }
  }

  @ApiOperation({ summary: i18n.t('app-flow.flow-board-data.flow-board-data.12153237-4') })
  @Put()
  async save(@Body() param: FlowBoardDataSaveDto) {
    return await this.boardDataDao.save({
      ...param,
      dataHash: md5(param.data),
    })
  }
}
